package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 * @Author： wz
 * @Date: 2019-09-16 00:03
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        //给哪些扣库存，扣库存的逻辑是什么？跟表有关
        List<CartProductDto> userCartInfo = createOrderContext.getCartProductDtoList();

        //convertRequest2Ctx 里面没有做productIds的转化，所以这里需要我们去做

        List<Long> buyProductIds = userCartInfo.stream().map(CartProductDto::getProductId).collect(Collectors.toList());

        //根据商品id排序，方便后面的同步遍历
        userCartInfo.sort(new Comparator<CartProductDto>() {
            @Override
            public int compare(CartProductDto o1, CartProductDto o2) {
                return (o1.getProductId() < o2.getProductId()) ? -1 : ((o1.getProductId() == o2.getProductId()) ? 0 : 1);
            }
        });

        buyProductIds.sort(Long::compareTo);

        //锁定库存
        List<Stock> oldStockInfo = stockMapper.findStocksForUpdate(buyProductIds);

        //判断不合法
        if (CollectionUtils.isEmpty(oldStockInfo)) {
            throw new BizException("库存未初始化");
        }

        if (oldStockInfo.size() != buyProductIds.size()) {
            throw new BizException("部分商品库存未初始化");
        }

        //扣减库存
        int cartSize = userCartInfo.size();
        for (int i = 0; i < cartSize; i++) {
            CartProductDto cartProductDto = userCartInfo.get(i);
            Stock stock = oldStockInfo.get(i);

            //用户购买行为判断
            validateBuy(cartProductDto, stock);

            //stockMapper里面传入的stock的LockCount是 + 商品数量，StockCount是-商品数量
            Long buyNum = cartProductDto.getProductNum();
            stock.setStockCount(-buyNum);
            stock.setLockCount(buyNum.intValue());

            stockMapper.updateStock(stock);

        }
        //往上下文里面设置 productIds
        createOrderContext.setBuyProductIds(buyProductIds);

        return true;
    }

    private void validateBuy(CartProductDto cartProductDto, Stock stock) {
        // 超过购买限制
        if (cartProductDto.getProductNum() > stock.getRestrictCount()) {
            throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
        }
        // 超过库存
        if (cartProductDto.getProductNum() > stock.getStockCount()) {
            throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
        }
    }
}